<?php

namespace app\jxcshop\controller\sys_admin;

use app\AdminController;
use app\distribution\controller\sys_admin\LevelApply;
use app\jxcshop\model\UsersModel;

use app\distribution\model\DividendRoleModel;
use app\distribution\model\DividendModel;
use app\publics\controller\api\Areas;
use app\weixin\model\WeiXinUsersModel;


use app\jxcshop\model\UsersLevelApplyModel;


use think\Db;
use think\facade\Cache;

/**
 * 会员管理
 * Class Index
 * @package app\store\controller
 */
class Users extends AdminController
{
    public $is_ban = 0;
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new UsersModel();
    }
    /*------------------------------------------------------ */
    //-- 首页
    /*------------------------------------------------------ */
    public function index()
    {
        $this->assign('rode_id', input('rode_id', 0, 'intval'));
        $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);

        //首页跳转时间
        $start_date = input('start_time', '0', 'trim');
        $end_date = input('end_time', '0', 'trim');
        if ($start_date || $end_date) {

            $this->assign("start_date", str_replace('_', '/', $start_date));
            $this->assign("end_date", str_replace('_', '/', $end_date));
        }
        $this->assign("roleOpt", arrToSel($this->roleList, $this->search['roleId']));
        $this->assign("levelOpt", arrToSel($this->levelList, $this->search['levelId']));
        return $this->fetch('sys_admin/users/index');
    }

    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false, $is_ban = -1)
    {
        $this->search['roleId'] = input('rode_id', -1);
        $this->search['levelId'] = input('level_id', 0, 'intval');
        $this->search['keyword'] = input("keyword");
        $this->search['time_type'] = input("time_type");

        $this->assign("is_ban", $this->is_ban);
        $this->assign("search", $this->search);
        $DividendRoleModel = new DividendRoleModel();
        $this->roleList = $DividendRoleModel->getRows();
        $this->assign("roleList", $this->roleList);

        $where[] = ' is_ban = ' . $this->is_ban;
        $reportrange = input('reportrange');
        $search['start_time'] = input('start_time', '', 'trim');
        $search['end_time'] = input('end_time', '', 'trim');
        if (empty($search['start_time']) == false) {
            $dtime[0] = str_replace('_', '-', $search['start_time']);
            $dtime[1] = str_replace('_', '-', $search['end_time']);
        } elseif (empty($reportrange) == false) {
            $dtime = explode('-', $reportrange);
        }
        if (empty($dtime) == false) {
            $dtime[0] = strtotime($dtime[0]);
            $dtime[1] = strtotime($dtime[1]) + 86399;
        }
        switch ($this->search['time_type']) {
            case 'reg_time':
                $where[] = ' u.reg_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            case 'login_time':
                $where[] = ' u.login_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            case 'buy_time':
                $where[] = ' u.last_buy_time between ' . $dtime[0] . ' AND ' . $dtime[1];
                break;
            default:
                break;
        }

        if ($this->search['roleId'] == 'all_role') {
            $where[] = ' u.role_id > 0 ';
        } elseif ($this->search['roleId'] >= 0) {
            $where[] = ' u.role_id = ' . $this->search['roleId'] * 1;
        }
        $where[] = ' u.jxcshopgudong = 1 ';

        if (empty($this->search['keyword']) == false) {
            if (is_numeric($this->search['keyword'])) {
                $where[] = " ( u.user_id = '" . ($this->search['keyword']) . "' or mobile like '" . $this->search['keyword'] . "%' )";
            } else {
                $where[] = " ( u.user_name like '" . $this->search['keyword'] . "%' or u.nick_name like '" . $this->search['keyword'] . "%' )";
            }
        }
        $export = input('export', 0, 'intval');
        if ($export > 0) {
            return $this->exportList($where);
        }
        $sort_by = input("sort_by", 'DESC', 'trim');
        $order_by = 'u.user_id';
        $viewObj = $this->Model
            ->alias('u')
            ->join("users_account uc", 'u.user_id=uc.user_id', 'left')
            ->where(join(' AND ', $where))->field('u.*,uc.balance_money,uc.use_integral,uc.total_integral,uc.integral_money')->order($order_by . ' ' . $sort_by);

        $data = $this->getPageList($this->Model, $viewObj);

        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['profit_pid'] = $this->getProfit($value['profit_pid']);
        }

        $levelList = (new UsersLevelApplyModel)->getRows();
        $data['order_by'] = $order_by;
        $data['sort_by'] = $sort_by;
        $this->assign("data", $data);
        $this->assign("levelList", $levelList);
        $this->assign("search", $this->search);
        if ($runData == false) {
            $data['content'] = $this->fetch('sys_admin/users/list')->getContent();
            return $this->success('', '', $data);
        }
        return true;
    }

    /**
     * 获取所属上级 getProfit
     * @param int $pid [上级id]
     * @return void
     */
    public function getProfit($pid = 0)
    {
        $profituser = $this->Model->where('user_id', $pid)->field('role_id,profit_pid,user_id')->find();
        if ($profituser['role_id'] <= 1) {
            if ($profituser['profit_pid'] == 0) {
                return 0;
            }
            return $this->getProfit($profituser['profit_pid']);
        }
        return $profituser['user_id'];
    }

    /*------------------------------------------------------ */
    //-- 会员管理
    /*------------------------------------------------------ */
    public function info()
    {
        $user_id = input('user_id/d');
        if ($user_id < 1) return $this->error('获取用户ID传值失败！');
        $row = $this->Model->info($user_id);
        if (empty($row)) return $this->error('用户不存在！');
        $row['wx'] = (new WeiXinUsersModel)->where('user_id', $user_id)->find();
        $this->assign("userShareStats", $this->Model->userShareStats($user_id));
        $row['user_address'] = (new UserAddressModel)->where('user_id', $user_id)->select();
        $this->assign('row', $row);
        $this->assign('d_level', config('config.dividend_level'));
        $DividendRoleModel = new DividendRoleModel();
        $this->assign("roleList", $DividendRoleModel->getRows());
        $this->assign("teamCount", $this->Model->teamCount($user_id));
        $where[] = ['dividend_uid', '=', $user_id];
        $where[] = ['status', 'in', [2, 3]];
        $DividendModel = new DividendModel();
        $dividend_amount = $DividendModel->where($where)->sum('dividend_amount');
        $this->assign("wait_money", $dividend_amount);
        $has_order = 0;
        //判断订单模块是否存在
        if (class_exists('app\shop\model\OrderModel')) {
            $has_order = 1;
            $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
            $this->assign("end_date", date('Y/m/d'));
        }
        $this->assign('has_order', $has_order);
        $UsersLevelAgentModel = new UsersLevelAgentModel();
        $users_level_agent = $UsersLevelAgentModel->getRows($user_id);
        $this->assign("users_level_agent", $users_level_agent);
        $UsersLevelModel = new UsersLevelModel();
        $this->levelList = $UsersLevelModel->getRows();
        $this->assign("levelList", $this->levelList);
        return $this->fetch('sys_admin/users/info');
    }


    /*
     *
     * 获取地址全名
     */
    public function getAreasallname($id){

        if(empty($id)){
            return '无';
        }
        //$areasObj = new Areas();
        $areasRes = Db::table('t_areas')->where('id',$id)->find();
        $type = $areasRes['type'];
        if($type == 1){
            return $areasRes['name'];
        }else if($type == 2){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            return $pidRes['name'].','.$areasRes['name'];
        }else if($type == 3){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            return $pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }else if($type == 4){
            $pidRes = Db::table('t_areas')->where('id',$areasRes['pid'])->find();
            $pidpidRes = Db::table('t_areas')->where('id',$pidRes['pid'])->find();
            $pidpidpidRes = Db::table('t_areas')->where('id',$pidpidRes['pid'])->find();
            return $pidpidpidRes['name'].','.$pidpidRes['name'].','.$pidRes['name'].','.$areasRes['name'];
        }

    }




    /*------------------------------------------------------ */
    //-- 执行统计
    /*------------------------------------------------------ */
    public function evalStat()
    {
        $reportrange = input('reportrange', '2019/01/01 - 2019/03/21', 'trim');
        $user_id = input('user_id', '0', 'intval');

        $dtime = explode('-', $reportrange);
        $UsersBindSuperiorModel = new UsersBindSuperiorModel();
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET('" . $user_id . "',superior)")];
        $user_ids = $UsersBindSuperiorModel->where($where)->column('user_id');

        $oWhere[] = ['o.user_id', 'in', $user_ids];
        $oWhere[] = ['o.order_status', '=', 1];
        $oWhere[] = ['o.add_time', 'between', [strtotime($dtime[0]), strtotime($dtime[1]) + 86399]];
        $viewObj = (new \app\shop\model\OrderModel)->alias('o')->field('o.user_id,o.order_id,o.user_id,o.order_amount,o.dividend_amount,og.goods_name,og.goods_id,og.goods_name,og.goods_number,og.shop_price,og.sale_price');
        $viewObj->join("shop_order_goods og", 'og.order_id=o.order_id', 'left');
        $rows = $viewObj->where($oWhere)->select()->toArray();
        $result['buyGoods'] = [];
        $nowUser = [];

        $order_ids = $user_order_ids = [];
        $buy_ser_ids = [];
        $team_amount = [];
        $user_amount = [];
        foreach ($rows as $row) {
            if ($row['goods_id'] < 1) continue;
            $order_ids[$row['order_id']] = 1;
            $buy_ser_ids[$row['user_id']] = 1;
            $result['buyGoods'][$row['goods_id']]['goods_name'] = $row['goods_name'];
            $result['buyGoods'][$row['goods_id']]['num'] += $row['goods_number'];
            $result['buyGoods'][$row['goods_id']]['price'] += ($row['sale_price'] * $row['goods_number']);
            $team_amount[$row['order_id']]['dividend_amount'] = $row['dividend_amount'];
            $team_amount[$row['order_id']]['order_amount'] = $row['order_amount'];
            if ($row['user_id'] == $user_id) {
                $nowUser['buyGoods'][$row['goods_id']]['goods_name'] = $row['goods_name'];
                $nowUser['buyGoods'][$row['goods_id']]['num'] += $row['goods_number'];
                $nowUser['buyGoods'][$row['goods_id']]['price'] += ($row['sale_price'] * $row['goods_number']);
                $user_order_ids[$row['order_id']] = 1;
                $user_amount[$row['order_id']]['dividend_amount'] = $row['dividend_amount'];
                $user_amount[$row['order_id']]['order_amount'] = $row['order_amount'];
            }
        }

        $result['dividend_amount'] = 0;
        $result['order_amount'] = 0;
        foreach ($team_amount as $tarr) {
            $result['dividend_amount'] += $tarr['dividend_amount'];
            $result['order_amount'] += $tarr['order_amount'];
        }
        $nowUser['dividend_amount'] = 0;
        $nowUser['order_amount'] = 0;
        foreach ($user_amount as $uarr) {
            $nowUser['dividend_amount'] += $uarr['dividend_amount'];
            $nowUser['order_amount'] += $uarr['order_amount'];
        }

        $result['code'] = 1;
        $result['reportrange'] = $reportrange;
        $result['order_num'] = count($order_ids);
        $result['buy_user_num'] = count($buy_ser_ids);
        $nowUser['order_num'] = count($user_order_ids);
        $result['nowUser'] = $nowUser;
        return $this->ajaxReturn($result);
    }


    /*------------------------------------------------------ */
    //-- 设门店股东
    /*------------------------------------------------------ */
    public function setJxcshopgudong()
    {
        $user_id = input('user_id', 0, 'intval');
        $row = $this->Model->info($user_id);
        if ($this->request->isPost()) {
            $data['jxcshopgudong'] = input('jxcshopgudong');
            $res = $this->Model->upInfo($user_id, $data);
            if ($res < 1) return $this->error('操作失败,请重试.');
            $info = "设置门店股东";
            $this->_log($user_id, $info, 'member');
            return $this->success('修改成功！', 'reload');
        }
        $this->assign("row", $row);

        return $this->fetch('sys_admin/users/set_jxcshopgudong');
    }


    /*------------------------------------------------------ */
    //-- 搜索会员
    /*------------------------------------------------------ */
    public function searchBox()
    {
        $this->assign('rode_id', input('rode_id', 0, 'intval'));
        $this->assign("start_date", date('Y/m/01', strtotime("-1 months")));
        $this->assign("end_date", date('Y/m/d'));
        $this->getList(true);

        //首页跳转时间
        $start_date = input('start_time', '0', 'trim');
        $end_date = input('end_time', '0', 'trim');
        if ($start_date || $end_date) {

            $this->assign("start_date", str_replace('_', '/', $start_date));
            $this->assign("end_date", str_replace('_', '/', $end_date));
        }

        return $this->fetch('sys_admin/users/search_box');
    }

    /*------------------------------------------------------ */
    //-- 搜索会员
    /*------------------------------------------------------ */
    public function getSearchList()
    {
        $this->getList(true);
        $this->data['content'] = $this->fetch('sys_admin/users/search_list')->getContent();
        return $this->success('', '', $this->data);
    }

    /*------------------------------------------------------ */
    //-- 新增会员
    /*------------------------------------------------------ */
    public function addUser()
    {
        if ($this->request->isPost()) {
            $inArr = input('post.');
            if (!$inArr['password'] || !$inArr['password_again']) {
                return $this->error('请输入密码');
            }
            if ($inArr['password'] != $inArr['password_again']) {
                return $this->error('两次密码不一致，请重新输入');
            }
            unset($inArr['password_again']);
            session('share_token', '');
            $res = $this->Model->register($inArr, 0, true, $this);
            if ($res === true) {
                return $this->success('添加成功.');
            }
            return $this->error($res);
        }
        return $this->fetch();
    }
    /*------------------------------------------------------ */
    //-- 修改手机号码
    /*------------------------------------------------------ */
    public function upMobile()
    {
        $user_id = input('user_id');
        $user = $this->Model->find($user_id);
        if (empty($user)) {
            return $this->error('用户不存在.');
        }
        if ($this->request->isPost()) {
            $mobile = input('mobile');
            if (checkMobile($mobile) == false) {
                // return '手机号码不正确.';
                return $this->error('手机号码不正确');
            }
            $count = $this->Model->where('mobile', $mobile)->count('user_id');
            if ($count > 0) {
                return $this->error('手机号已存在');
            }
            $upDate['mobile'] = $mobile;
            $res = $this->Model->where('user_id', $user_id)->update($upDate);
            if ($res < 1) {
                return $this->error('未知错误，处理失败.');
            }
            $this->Model->cleanMemcache($user_id);
            $text = '原手机号:' . $user['mobile'] . '改为' . $mobile;
            $this->_log($user_id, $text);
            return $this->success('修改成功.');
        }
        $this->assign('user', $user);
        return $this->fetch('sys_admin/users/up_mobile');
    }
    /*------------------------------------------------------ */
    //-- 获取用户操作日志
    /*------------------------------------------------------ */
    public function getOptLogList()
    {
        $user_id = input('user_id', 0, 'intval');
        if ($user_id < 1) {
            return $this->error('代理ID不能为空');
        }
        $logs = (new LogSysModel)->where('edit_id', $user_id)->order('log_id DESC')->select()->toArray();
        foreach ($logs as $key => $log) {
            $log['admin_info'] = $log['user_id'] . '-' . adminInfo($log['user_id']);
            $log['log_time'] = dateTpl($log['log_time']);
            $logs[$key] = $log;
        }
        $data['list'] = $logs;
        return $this->success('ok', '', $data);
    }
}
